define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'clipboard', 'template','common/jszip',"common/filesaver"], function ($, undefined, Backend, Table, Form,ClipboardJS,Template, Jszip, Filesaver) {
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'auth/admin/index',
                    add_url: 'auth/admin/add',
                    edit_url: 'auth/admin/edit',
                    del_url: 'auth/admin/del',
                    multi_url: 'auth/admin/multi',
                }
            });
            var table = $("#table");
            //在表格内容渲染完成后回调的事件
            table.on('post-body.bs.table', function (e, json) {
                $("tbody tr[data-index]", this).each(function () {
                    if (parseInt($("td:eq(1)", this).text()) == Config.admin.id) {
                        $("input[type=checkbox]", this).prop("disabled", true);
                    }
                });
            });
            //当表格数据加载完成时
            table.on('load-success.bs.table', function (e, data) {
                //这里可以获取从服务端获取的JSON数据
                //  console.log(data);
                //这里我们手动设置底部的值
                $("#all").text(data.extend.total);

                if(data.html!=''&&data.html!=null){
                    $("#createhtml").html(data.html);
                }

            });

            //打包命令 php think min -m all -r all

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pagination: false,
                search: false,
                commonSearch: false,
                sortName: 'weigh DESC,id DESC',
                searchFormVisible: Fast.api.query("model_id") ? true : false,
                fixedColumns: true,
                fixedRightNumber: 1,
                dblClickToEdit: false, //是否启用双击编辑
                clickToSelect: false, //是否启用点击选中
                columns: [
                    [
                        /*data-params='{"custom[status]":"1"}'*/
                        {
                            field: 'state', checkbox: true, formatter: function (value, row, index) {
                                if (row.state === false) {
                                    return {
                                        disabled: true,
                                    }
                                } else {
                                    return {
                                        disabled: false,
                                    }
                                }
                            }
                        },
                        {
                            field: 'user_id',
                            title: __('User_id'),
                            visible: false,
                            //data-primary-key="code"
                            addclass: 'selectpage',
                            extend: 'data-source="customer.customer/index" data-field="username"  data-params=\'{"custom[status]":"normal","custom[type]":"1"}\' ',
                            operate: '=',
                            formatter: Table.api.formatter.search
                        },
                        {
                            field: 'model_id', title: __('Model'), visible: false, align: 'left', addclass: "selectpage", extend: "data-source='cms/modelx/index' data-field='name'"
                        },
                        {
                            field: 'title', title: __('Title'), align: 'left', customField: 'flag', formatter: function (value, row, index) {
                                return '<div class="archives-title"><a href="' + row.url + '" target="_blank"><span style="color:' + (row.style_color ? row.style_color : 'inherit') + ';font-weight:' + (row.style_bold ? 'bold' : 'normal') + '">' + value + '</span></a></div>' +
                                    '<div class="archives-label">' + Table.api.formatter.flag.call(this, row['flag'], row, index) + '</div>';
                            }
                        },
                        {
                            field: 'iscontribute', visible: ['channel', 'page', 'special'].indexOf(Config.source) < 0, title: __('Iscontribute'), searchList: {"1": __('Yes'), "0": __('No')}, formatter: function (value, row, index) {
                                return row.issystem && ["channel_ids", "image", "images", "tags", "content", "keywords", "description"].indexOf(row.name) === -1 ? "-" : Table.api.formatter.toggle.call(this, value, row, index);
                            }
                        },
                        {
                            field: 'status', title: __('Status'), formatter: function (value, row, index) {
                                return row.issystem ? "-" : Table.api.formatter.status.call(this, value, row, index);
                            }
                        },
                        {field: 'username', title: __('Username'),events: Controller.api.events.copy,formatter: Controller.api.formatter.copy},
                        {field: 'score', title: __('Score'), operate:false,formatter:function (value) {
                                return '<strong style="color: blue">+'+value+'</strong>';
                            }},
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'addtabs',
                                    text: __('报价单'),
                                    title: __('应用报价单'),
                                    classname: 'btn btn-xs btn-warning btn-addtabs',
                                    icon: 'fa fa-dashboard',
                                    extend: 'data-toggle="tooltip"',
                                    url: 'smsapp.apps_quotation/index?appid={ids}'
                                }
                            ],
                            formatter: function (value, row, index) { //隐藏自定义的视频按钮
                                var that = $.extend({}, this);
                                var table = $(that.table).clone(true);
                                //权限判断
                                if(Config.chapter != true){  //通过Config.chapter 获取后台存的chapter
                                    console.log('没有视频权限');
                                    $(table).data("operate-addtabs", null);
                                    that.table = table;
                                }else{
                                    console.log('有视频权限');
                                }
                                return Table.api.formatter.operate.call(that, value, row, index);
                            }
                        },

                        {field: 'description', title: __('Msg'), operate: 'LIKE %...%',
                            formatter : function(value, row, index, field){
                                return "<span style='display: block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;' data-toggle='tooltip' data-original-title='" + row.msg + "'>" + value + "</span>";
                            },
                            cellStyle : function(value, row, index, field){
                                return {
                                    css: {
                                        "white-space": "nowrap",
                                        "text-overflow": "ellipsis",
                                        "overflow": "hidden",
                                        "cursor":"pointer",
                                        "max-width":"200px"
                                    }
                                };
                            }
                        },
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: function (value, row, index) {
                                if(row.id == Config.admin.id){
                                    return '';
                                }
                                return Table.api.formatter.operate.call(this, value, row, index);
                            }},
                        {
                            field: 'operate', title: __('Operate'), table: table,operate: false,
                            events: {
                                'click .btn-false': function (e, value, row) {
                                    var m='确认该笔充值已失败吗？';
                                    Layer.confirm(m,function (index) {
                                        Layer.close(index);
                                        Fast.api.ajax({
                                            url: "finance/charger_check/falsed",
                                            data: {id: row.id},
                                        }, function (data, ret) {
                                            table.bootstrapTable('refresh');
                                        },function (data,ret) {
                                            table.bootstrapTable('refresh');
                                        });
                                    });
                                    return false;
                                },
                                'click .btn-daozhang': function (e, value, row) {
                                    var m='<font color="green">若未充值相对应金额</font><br><font color="green">则在点击确认后减少到账积分！</font><br>需充值金额：'+row.money+' U<br>'+'应该到账积分：'+row.score+'<br>或需充值卢比：'+row.lubi+'<br>';
                                    var ji=row.score;

                                    Layer.confirm(m,{title:'确认该笔充值已到账吗？'},function (index) {
                                        Layer.close(index);
                                        layer.prompt({title: '到账积分！',value:ji,formType: 3, btn: ["确认","取消"]}, function(value, indexx){
                                            Layer.close(indexx);
                                            Fast.api.ajax({
                                                url: "finance/charger_check/daozhang",
                                                data: {id: row.id,score:value},
                                            }, function (data, ret) {
                                                table.bootstrapTable('refresh');
                                            },function (data,ret) {
                                                table.bootstrapTable('refresh');
                                            });
                                        });
                                    });
                                    return false;
                                }
                            },
                            buttons: [
                                {
                                    name: 'index',
                                    text: __('到账'),
                                    classname: 'btn btn-xs btn-info btn-daozhang',
                                    icon:'fa fa-check',
                                    title:__('确认该笔充值已到账'),
                                    visible: function (row) {
                                        if (row.state == 1) return true;
                                        return false;
                                    },
                                },
                                {
                                    name: 'bai',
                                    text: __('失败'),
                                    classname: 'btn btn-xs btn-danger btn-false',
                                    icon:"fa  fa-times",
                                    title:__('该笔转账失败'),
                                    visible: function (row) {
                                        if (row.state == 1) return true;
                                        return false;
                                    },
                                },
                                {
                                    name: 'index',
                                    text: __('团队'),
                                    classname: 'btn btn-xs btn-info btn-dialog',
                                    extend: 'data-area=\'["80%","85%"]\' ',
                                    title: __('查看当前会员的团队'),
                                    url: 'user/user_relation/index?uid={ids}'
                                },

                            ],
                            formatter: function (value, row, index) { //隐藏自定义的视频按钮
                                var that = $.extend({}, this);
                                var table = $(that.table).clone(true);
                                //权限判断
                                if(Config.chapter != true){  //通过Config.chapter 获取后台存的chapter
                                    console.log('没有视频权限');
                                    $(table).data("operate-video", null);
                                    that.table = table;
                                }else{
                                    console.log('有视频权限');
                                }
                                return Table.api.formatter.operate.call(that, value, row, index);
                            }
                        },
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);


            //单选按钮
            $('input:radio[name="row[type]"]').click(function(){
                var checkValue = $('input:radio[name="row[type]"]:checked').val();
                if (checkValue==0){
                    $(".per_1").hide(0);
                    $(".per_3").show(0);
                }else{
                    $(".per_3").hide(0);
                    $(".per_1").show(0);
                }
            });

            //批量下载图片
            $("#downloaderweima").on("click",function(res){
                var zip = new Jszip();
                var img = zip.folder("images"); // 生成图片文件夹
                var all = table.bootstrapTable('getSelections'); // 获取表格全部选中的数据
                if(all.length < 1){
                    Layer.msg("请选择要下载的二维码");
                    return false;
                }
                for(var i=0; i< all.length ;i++)
                {
                    var img_arr = all[i].qrcode.split(','); //分割开数据
                    img.file(all[i].id+".png", img_arr[1], {base64:true});//图片批量写入文件
                }
                zip.generateAsync({type:"blob"}).then(function(content) {
                    // see FileSaver.js
                    saveAs(content, "example.zip");
                });
            });

            //提取缩略图
            $(document).on("click", ".btn-getimage", function (a) {
                var image = $("<div>" + $("#c-content").val() + "</div>").find('img').first().attr('src');
                if (image) {
                    var obj = $("#c-image");
                    if (obj.val() != '') {
                        Layer.confirm("缩略图已存在，是否替换？", {icon: 3}, function (index) {
                            obj.val(image).trigger("change");
                            layer.close(index);
                            Toastr.success("提取成功");
                        });
                    } else {
                        obj.val(image).trigger("change");
                        Toastr.success("提取成功");
                    }

                } else {
                    Toastr.error("未找到任何图片");
                }
                return false;
            });

            //提取组图
            $(document).on("click", ".btn-getimages", function (a) {
                var image = $("<div>" + $("#c-content").val() + "</div>").find('img').first().attr('src');
                if (image) {
                    var imageArr = [];
                    $("<div>" + $("#c-content").val() + "</div>").find('img').each(function (i, j) {
                        if (i > 3) {
                            return false;
                        }
                        imageArr.push($(this).attr("src"));
                    });
                    image = imageArr.slice(0, 4).join(",");
                    var obj = $("#c-images");
                    if (obj.val() != '') {
                        Layer.confirm("文章组图已存在，是否替换？", {icon: 3}, function (index) {
                            obj.val(image).trigger("change");
                            layer.close(index);
                            Toastr.success("提取成功");
                        });
                    } else {
                        obj.val(image).trigger("change");
                        Toastr.success("提取成功");
                    }

                } else {
                    Toastr.error("未找到任何图片");
                }
                return false;
            });


            // 踢下线
            $(document).on("click", ".btn-xia", function () {
                var ids = Table.api.selectedids(table);
                var m = '确定强制下线选择的用户吗？';
                Layer.confirm(m, function (index) {
                    Layer.close(index);
                    Fast.api.ajax({
                        url: "user/user/pause",
                        data: {ids: ids},
                    }, function (data, ret) {
                        table.bootstrapTable('refresh');
                    });
                });
                return false;
                // alert(ids)
                // Table.api.multi("changestatus", ids.join(","), table, this);
            });

            },
        add: function () {

            //事件监听
            $("#c-code").data("eSelect", function(row){
                //后续操作
                $("#c-s_name").val(row.c_name);
            });
            //自定义行模板
            $("#c-code").data("format-item", function(row){
                return row.c_name + " - " + row.code;
            });
            Form.api.bindevent($("form[role=form]"));
        },
        edit: function () {
            Form.api.bindevent($("form[role=form]"));
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            formatter:{
                copy:function (value,row,index) {
                    var width = this.width != undefined ? (this.width.match(/^\d+$/) ? this.width + "px" : this.width) : "250px";
                    return '<button class="btn btn-copy btn-xs bg-success" data-clipboard-text="'+value+'" data-original-title="点击复制" data-toggle="tooltip">' +
                        '<div style="white-space: nowrap; text-overflow:ellipsis; overflow: hidden; max-width:"'+ width +'";>'+ value +' </div>' +
                        '</button>';
                }
            },
            events:{
                copy:{
                    'click .btn-copy':function (e,value,row,index) {
                        var clipboard=new ClipboardJS(".btn");
                        Toastr.info("复制成功");
                    }
                }
            }
        }
    };
    return Controller;
});
